<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绑定表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入绑定表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:coding:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:coding:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:coding:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:coding:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="codingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则ID" align="center" prop="ruleId" />
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="绑定表名" align="center" prop="tableName" />
      <el-table-column label="绑定字段" align="center" prop="fieldName" />
      <el-table-column label="编码预览" align="center" prop="preview" width="200">
        <template slot-scope="scope">
          <el-tag type="info" size="mini">{{ scope.row.preview || '点击生成预览' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="连接符" align="center" prop="separator" width="80" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coding:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coding:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改编码规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定表名" prop="tableName">
              <el-input v-model="form.tableName" placeholder="请输入绑定表名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定字段" prop="fieldName">
              <el-input v-model="form.fieldName" placeholder="请输入绑定字段名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="连接符" prop="separator">
              <el-select v-model="form.separator" placeholder="请选择连接符">
                <el-option label="- (横线)" value="-" />
                <el-option label="_ (下划线)" value="_" />
                <el-option label="无连接符" value="" />
                <el-option label=". (点)" value="." />
                <el-option label="| (竖线)" value="|" />
                <el-option label="* (星号)" value="*" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="编码段配置">
          <el-table :data="form.segments" style="width: 100%">
            <el-table-column label="顺序" width="60">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="段类型" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.segmentType" placeholder="选择类型" @change="handleSegmentTypeChange(scope.row)">
                  <el-option label="常量" value="CONSTANT" />
                  <el-option label="流水号" value="SERIAL" />
                  <el-option label="日期" value="DATE" />
                  <el-option label="时间戳" value="TIMESTAMP" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="配置值">
              <template slot-scope="scope">
                <!-- 常量配置 -->
                <el-input 
                  v-if="scope.row.segmentType === 'CONSTANT'"
                  v-model="scope.row.segmentValue" 
                  placeholder="请输入常量值" 
                  size="mini"
                />
                <!-- 日期配置 -->
                <el-select 
                  v-else-if="scope.row.segmentType === 'DATE'"
                  v-model="scope.row.dateFormat" 
                  placeholder="选择日期格式" 
                  size="mini"
                >
                  <el-option label="yyyyMMdd" value="yyyyMMdd" />
                  <el-option label="yyyy" value="yyyy" />
                  <el-option label="yyyyMM" value="yyyyMM" />
                  <el-option label="MMdd" value="MMdd" />
                  <el-option label="yy" value="yy" />
                  <el-option label="yyMM" value="yyMM" />
                </el-select>
                <!-- 时间戳配置 -->
                <el-input-number 
                  v-else-if="scope.row.segmentType === 'TIMESTAMP'"
                  v-model="scope.row.timestampLength" 
                  :min="1" 
                  :max="13" 
                  placeholder="截取长度" 
                  size="mini"
                />
                <!-- 流水号配置 -->
                <div v-else-if="scope.row.segmentType === 'SERIAL'" style="display: flex; gap: 5px;">
                  <el-input-number v-model="scope.row.serialLength" :min="1" :max="10" placeholder="长度" size="mini" style="width: 80px;" />
                  <el-input-number v-model="scope.row.serialStart" :min="1" placeholder="起始值" size="mini" style="width: 80px;" />
                  <el-select v-model="scope.row.resetType" placeholder="重置" size="mini" style="width: 80px;">
                    <el-option label="不重置" value="NONE" />
                    <el-option label="每日" value="DAILY" />
                    <el-option label="每月" value="MONTHLY" />
                    <el-option label="每年" value="YEARLY" />
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="moveUp(scope.$index)" :disabled="scope.$index === 0">上移</el-button>
                <el-button size="mini" type="text" @click="moveDown(scope.$index)" :disabled="scope.$index === form.segments.length - 1">下移</el-button>
                <el-button size="mini" type="text" @click="removeSegment(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="mini" @click="addSegment" style="margin-top: 10px;">添加编码段</el-button>
          <el-button type="success" size="mini" @click="previewCode" style="margin-top: 10px; margin-left: 10px;">预览编码</el-button>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoding, getCoding, delCoding, addCoding, updateCoding } from "@/api/system/coding";

export default {
  name: "Coding",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 编码规则表格数据
      codingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        tableName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        tableName: [
          { required: true, message: "绑定表名不能为空", trigger: "blur" }
        ],
        fieldName: [
          { required: true, message: "绑定字段名不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询编码规则列表 */
    getList() {
      this.loading = true;
      listCoding(this.queryParams).then(response => {
        this.codingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        ruleName: null,
        tableName: null,
        fieldName: null,
        separator: "-",
        status: "0",
        remark: null,
        segments: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加编码规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids
      getCoding(ruleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改编码规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != null) {
            updateCoding(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoding(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除编码规则编号为"' + ruleIds + '"的数据项？').then(function() {
        return delCoding(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/coding/export', {
        ...this.queryParams
      }, `coding_${new Date().getTime()}.xlsx`)
    },
    /** 预览编码 */
    handlePreview(row) {
      // 这里可以调用后端接口生成预览编码
      this.$modal.msgInfo("编码预览功能开发中...");
    },
    /** 添加编码段 */
    addSegment() {
      this.form.segments.push({
        segmentOrder: this.form.segments.length + 1,
        segmentType: 'CONSTANT',
        segmentValue: '',
        dateFormat: 'yyyyMMdd',
        timestampLength: 10,
        serialLength: 4,
        serialStart: 1,
        resetType: 'NONE'
      });
    },
    /** 删除编码段 */
    removeSegment(index) {
      this.form.segments.splice(index, 1);
      // 重新排序
      this.form.segments.forEach((segment, idx) => {
        segment.segmentOrder = idx + 1;
      });
    },
    /** 上移编码段 */
    moveUp(index) {
      if (index > 0) {
        const temp = this.form.segments[index];
        this.$set(this.form.segments, index, this.form.segments[index - 1]);
        this.$set(this.form.segments, index - 1, temp);
        // 重新排序
        this.form.segments.forEach((segment, idx) => {
          segment.segmentOrder = idx + 1;
        });
      }
    },
    /** 下移编码段 */
    moveDown(index) {
      if (index < this.form.segments.length - 1) {
        const temp = this.form.segments[index];
        this.$set(this.form.segments, index, this.form.segments[index + 1]);
        this.$set(this.form.segments, index + 1, temp);
        // 重新排序
        this.form.segments.forEach((segment, idx) => {
          segment.segmentOrder = idx + 1;
        });
      }
    },
    /** 编码段类型变化处理 */
    handleSegmentTypeChange(segment) {
      // 根据类型重置相关字段
      if (segment.segmentType === 'CONSTANT') {
        segment.segmentValue = '';
      } else if (segment.segmentType === 'DATE') {
        segment.dateFormat = 'yyyyMMdd';
      } else if (segment.segmentType === 'TIMESTAMP') {
        segment.timestampLength = 10;
      } else if (segment.segmentType === 'SERIAL') {
        segment.serialLength = 4;
        segment.serialStart = 1;
        segment.resetType = 'NONE';
      }
    },
    /** 预览编码 */
    previewCode() {
      // 简单的前端预览逻辑
      let preview = '';
      this.form.segments.forEach((segment, index) => {
        if (index > 0 && this.form.separator) {
          preview += this.form.separator;
        }
        
        if (segment.segmentType === 'CONSTANT') {
          preview += segment.segmentValue || 'CONST';
        } else if (segment.segmentType === 'DATE') {
          const now = new Date();
          const format = segment.dateFormat || 'yyyyMMdd';
          if (format === 'yyyyMMdd') {
            preview += now.getFullYear() + String(now.getMonth() + 1).padStart(2, '0') + String(now.getDate()).padStart(2, '0');
          } else if (format === 'yyyy') {
            preview += now.getFullYear();
          } else if (format === 'yyyyMM') {
            preview += now.getFullYear() + String(now.getMonth() + 1).padStart(2, '0');
          } else {
            preview += format;
          }
        } else if (segment.segmentType === 'TIMESTAMP') {
          const timestamp = Date.now().toString();
          const length = segment.timestampLength || 10;
          preview += timestamp.substr(-length);
        } else if (segment.segmentType === 'SERIAL') {
          const length = segment.serialLength || 4;
          const start = segment.serialStart || 1;
          preview += String(start).padStart(length, '0');
        }
      });
      
      this.$modal.msgSuccess(`编码预览: ${preview}`);
    }
  }
};
</script>